<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use Closure;
use Exception;
use Illuminate\Http\Response;

class FormaterResponse
    {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
        {
        // Pre-Middleware Action

        $code     = 200;
        $msg      = 'success';
        $success  = true;
        $data     = [];
        $response = [];
        try {
            $response = $next($request);
            // 如果是 SSE 请求，直接返回响应，不做任何修改
            if ($request->is('analysis/page') || 
                (isset($response->headers) && $response->headers->get('Content-Type') === 'text/event-stream')) {
                return $response;
            }
            $data     = json_decode($response->getContent());
            //返回string时出错

            $data = !is_array($data) && $data == null ? $response->getContent() : $data;
            }
        catch ( ApiException $exception ) {

            if ($exception instanceof ApiException) {
                $code    = $exception->getCode();
                $msg     = $exception->getMessage();
                $success = false;
                $data    = $exception->getData();
                }
            }
        if ($response)
            if ($response->getStatusCode() != $code) {
                return $response;
                }

        $content = [
            'code'    => $code,
            'message' => $msg,
            'success' => $success,
            'data'    => $data
        ];

        return new Response($content);
        }
    }